<template>
  <div class="component-user-add-or-update user-update-dialog">
    <el-dialog
      v-model="visible"
      :title="
        !dataForm.userId
          ? $t('sysManagement.add')
          : $t('user.details')
      "
      :close-on-click-modal="false"
      width="70%"
      @close="onHandleDialogClose"
    >
      <!-- 用户信息 -->
      <div class="user-info-item">
        <el-divider
          class="info-title"
          content-position="left"
        >
          <h3>{{ $t('user.userInfo') }}</h3>
        </el-divider>
        <div class="info-content">
          <div class="base-info" />
          <div class="user-status" />
        </div>
      </div>
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        :label-width="
          $t('language') === 'language' ? '130px' : '80px'"
        @submit.prevent
        @keyup.enter="onSubmit()"
      >
        <el-container style="margin-top:20px">
          <el-aside width="210px">
            <el-form-item
              :label="$t('publics.profilePicture')"
              prop="pic"
            >
              <img
                v-if="!dataForm.pic"
                src="~@/assets/img/userImg.jpg"
                width="130"
                height="130"
                alt=""
              >
              <img
                v-else
                :src="checkFileUrl(dataForm.pic)"
                class="image"
                width="130"
                height="130"
                alt=""
                @error="dataForm.pic=''"
              >
            </el-form-item>
          </el-aside>
          <el-container>
            <el-main>
              <el-row>
                <el-col
                  :span="7"
                  justify="start"
                >
                  <el-form-item
                    :label="$t('users.name') + ':'"
                    prop="nickName"
                    size="small"
                  >
                    <span v-if="nameVisible">{{ dataForm.nickName }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    :label="$t('publics.status') + ':'"
                    size="small"
                    prop="status"
                  >
                    <span v-if="dataForm.status === 0">{{
                      $t("publics.disable")
                    }}</span>
                    <span v-if="dataForm.status === 1">{{
                      $t("publics.normal")
                    }}</span>
                    <span v-if="dataForm.status === 2">限制</span>
                  </el-form-item>
                </el-col>
                <el-col :span="9">
                  <el-form-item
                    :label="$t('user.registrationTime') + ':'"
                    prop="userRegtime"
                    size="small"
                  >
                    <span>{{ dataForm.userRegtime }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-main>
            <el-footer>
              <el-row
                :gutter="10"
              >
                <el-col :span="$t('language') === '语言' ? 4 : 5">
                  <div
                    v-if="isAuth('platform:coupon:sendUserCoupon')"
                    class="default-btn primary-btn"
                    @click="onUpdateCoupon()"
                  >
                    {{ $t("user.sendCoupons") }}
                  </div>
                </el-col>
                <el-col :span="$t('language') === '语言' ? 5: 7">
                  <div
                    class="default-btn primary-btn"
                    @click="onUpdateUserInfo()"
                  >
                    {{ $t("components.editInfo") }}
                  </div>
                </el-col>
                <el-col :span="$t('language') === '语言' ? 5 : 7">
                  <div
                    class="default-btn primary-btn"
                    @click="onUpdateTags()"
                  >
                    {{ $t("user.tagging") }}
                  </div>
                </el-col>
              </el-row>
            </el-footer>
          </el-container>
        </el-container>
        <el-form-item
          :label="$t('user.customerLabel')"
          prop="userTagParam "
        >
          <div v-if="userTag.length > 0">
            <el-tag
              v-for="tag in userTag"
              :key="tag.tagId"
              :closable="tag.tagType === 0"
              :disable-transitions="false"
              @close="onHandleClose(tag)"
            >
              {{ tag.tagName }}
            </el-tag>
          </div>
        </el-form-item>
        <!-- 账户资产 -->
        <el-divider content-position="left">
          <h3>{{ $t("user.accountAssets") }}</h3>
        </el-divider>
        <el-container>
          <el-main>
            <div>
              <h4>{{ $t("user.accountWallet") }}</h4>
              <br>
              <div>
                <span>{{ $t("user.currentBalance") }}：{{
                  dataForm.sumBalance
                }}</span>
                <span style="margin-left: 60px">{{ $t("user.cumulativeBalances") }}：{{
                  dataForm.currentBalance
                }}</span>
                <span style="margin-left: 60px">{{ $t("user.rechargeAmount") }}：{{
                  dataForm.rechargeAmount
                }}</span>
                <span style="margin-left: 60px">{{ $t("user.rechargeTimes") }}：{{
                  dataForm.rechargeTimes
                }}</span>
              </div>
              <br>
            </div>
            <br>
            <div>
              <h4>{{ $t("order.score") }}</h4>
              <br>
              <div>
                <span>{{ $t("user.currentScore") }}：{{ dataForm.score }}</span>
                <span style="margin-left: 60px">{{ $t("user.cumulativeScore") }}：{{
                  dataForm.sumScore
                }}</span>
              </div>
              <br>
            </div>
            <br>
            <div>
              <h4>
                {{ $t("user.coupons") }}
                <el-popover
                  placement="top"
                  width="200"
                  trigger="hover"
                  :content="$t('user.couponTip3')"
                >
                  <template #reference>
                    <el-icon><QuestionFilled /></el-icon>
                  </template>
                </el-popover>
              </h4>
              <br>
              <div>
                <span>
                  {{ $t("user.notUsed") }}：{{
                    couponUserParam.couponUsableNums
                  }}&nbsp;&nbsp;{{ $t("marketing.piece") }}
                </span>
                <span style="margin-left: 60px">
                  {{ $t("user.used") }}：{{
                    couponUserParam.couponUsedNums
                  }}&nbsp;&nbsp;{{ $t("marketing.piece") }}
                </span>
                <span style="margin-left: 60px">
                  {{ $t("user.invalid") }}：{{
                    couponUserParam.couponExpiredNums
                  }}&nbsp;&nbsp;{{ $t("marketing.piece") }}
                </span>
              </div>
              <br>
            </div>
          </el-main>
        </el-container>
        <el-divider content-position="left">
          <h3>{{ $t("user.otherInfo") }}</h3>
        </el-divider>
      </el-form>
      <div>
        <el-tabs>
          <el-tab-pane :label="$t('user.distributionInfo')">
            <div>
              <span>{{ $t("distributionMsg.invitees") }}：{{
                distributionUser.parentName
                  ? distributionUser.parentName
                  : "---"
              }}</span>
              <span style="margin-left: 40px">{{ $t("user.distributionTime") }}：{{
                distributionUser.bindTime ? distributionUser.bindTime : "---"
              }}</span>
              <span
                v-if="distributionUser.state == null"
                style="margin-left: 20px"
              >{{ $t("brand.status") }}：{{ "---" }}</span>
              <span
                v-else-if="distributionUser.state === -1"
                style="margin-left: 20px"
              >{{ $t("brand.status") }}：{{
                $t("distribUserWallet.perBan")
              }}</span>
              <span
                v-else-if="distributionUser.state > -1"
                style="margin-left: 20px"
              >{{ $t("brand.status") }}：{{
                [
                  $t("product.pendingReview"),
                  $t("brand.normal"),
                  $t("distribUserWallet.ban"),
                  $t("shop.auditFailed"),
                ][distributionUser.state]
              }}</span>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="$t('user.tradeDetails')">
            <trade-detail ref="tradeDetailRef" />
          </el-tab-pane>
          <el-tab-pane :label="$t('user.scoreDetails')">
            <score-detail ref="scoreDetailRef" />
          </el-tab-pane>
          <el-tab-pane :label="$t('user.balanceDetails')">
            <balance-detail ref="balanceDetailRef" />
          </el-tab-pane>
          <el-tab-pane :label="$t('user.couponDetails')">
            <coupon-detail ref="couponDetailRef" />
          </el-tab-pane>
          <el-tab-pane :label="$t('user.growthLog')">
            <growth-detail ref="growthDetailRef" />
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <div
          class="dialog-footer"
        >
          <div
            class="default-btn primary-btn"
            @click="onSubmit()"
          >
            {{ $t("remindPop.confirm") }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 送优惠券弹窗 -->
    <update-user-coupon
      v-if="updateCouponVisible"
      ref="updateCouponRef"
      :get-way="1"
      @refresh-data-list="onRefreshChange"
    />
    <!-- 打标签弹窗 -->
    <update-user-tags
      v-if="updateTagsVisible"
      ref="updateTagsRef"
      @refresh-data-list="onRefreshChange"
    />
    <!-- 修改用户基本信息 -->
    <update-user-info-component
      v-if="updateUserInfoVisible"
      ref="updateUserInfoRef"
      @refresh-user-info="onRefreshInfo"
    />
  </div>
</template>

<script setup>
import UpdateUserCoupon from './update-user-copon.vue'
import UpdateUserTags from './update-user-tags.vue'
import TradeDetail from './trade-detail.vue'
import ScoreDetail from './score-detail.vue'
import BalanceDetail from './balance-detail.vue'
import CouponDetail from './coupon-detail.vue'
import UpdateUserInfoComponent from './update-user-info.vue'
import GrowthDetail from './growth-detail.vue'
import { isAuth } from '@/utils'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
let isSubmit = false
const nameVisible = ref(true)
const updateCouponVisible = ref(false)
const updateUserInfoVisible = ref(false)
const updateTagsVisible = ref(false)
const dataForm = ref({
  userId: 0,
  nickName: '',
  pic: '',
  status: 1
})
const couponUserParam = ref({
  couponUsableNums: 0,
  couponUsedNums: 0,
  couponExpiredNums: 0
})
// 分销信息
const distributionUser = reactive({
  parentName: null,
  bindTime: null,
  state: null
})
const userTag = ref([{ agId: 0, tagName: null }])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const dataRule = {
}

const dataFormRef = ref(null)
const init = (id) => {
  dataForm.value.userId = id || 0
  // console.log('aa', id, dataForm)
  visible.value = true
  isSubmit = false
  clearVueData()
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
  if (dataForm.value.userId) {
    if (isSubmit) {
      return false
    }
    isSubmit = true
    http({
      url: http.adornUrl(`/admin/user/info/${dataForm.value.userId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      couponUserParam.value = dataForm.value.couponUserParam
      userTag.value = dataForm.value.userTagParam
      getDistribution()
      initTradeDetail(dataForm.value.userId)
      initScoreDetail(dataForm.value.userId)
      initBalanceDetail(dataForm.value.userId)
      initCouponDetail(dataForm.value.userId)
      initGrowthDetail(dataForm.value.userId)
    }).catch(() => {
      isSubmit = false
    })
  }
}
defineExpose({ init })
// 修改后刷新
const onRefreshChange = () => {
  init(dataForm.value.userId)
}
// 移除标签
const onHandleClose = (tag) => {
  http({
    url: http.adornUrl('/user/userTag/deleteUserTag'),
    method: 'delete',
    data: http.adornData({
      userId: dataForm.value.userId,
      userTagId: tag.tagId
    })
  }).then(() => {
    init(dataForm.value.userId)
  })
}
// 表单提交
const onSubmit = () => {
  visible.value = false
}
// 打标签
const updateTagsRef = ref(null)
const onUpdateTags = (id) => {
  const ids = id ? [id] : [dataForm.value.userId]
  updateTagsVisible.value = true
  nextTick(() => {
    updateTagsRef.value?.init(ids)
  })
}
const updateCouponRef = ref(null)
// 送优惠券
const onUpdateCoupon = (id) => {
  const ids = id ? [id] : [dataForm.value.userId]
  updateCouponVisible.value = true
  nextTick(() => {
    updateCouponRef.value?.init(ids)
  })
}
const updateUserInfoRef = ref(null)
// 修改用户信息
const onUpdateUserInfo = () => {
  updateUserInfoVisible.value = true
  nextTick(() => {
    updateUserInfoRef.value.init(dataForm.value)
  })
}

// 清空数据
const clearVueData = () => {
  // $refs['couponUserParam'].resetFields()
  Object.assign(couponUserParam.value, {
    couponUsableNums: 0,
    couponUsedNums: 0,
    couponExpiredNums: 0
  })
}
// 获取分销员信息
const getDistribution = () => {
  http({
    url: http.adornUrl(`/distribution/distributionUser/getInfo/${dataForm.value.userId}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      distributionUser.bindTime = data.bindTime
      distributionUser.state = data.state
      if (data.parentDistributionUser) {
        distributionUser.parentName = data.parentDistributionUser.nickName
      }
    }
  })
}

const tradeDetailRef = ref(null)
// 调用交易信息组件方法
const initTradeDetail = (id) => {
  tradeDetailRef.value?.init(id)
}
const scoreDetailRef = ref(null)
// 调用积分详情组件方法
const initScoreDetail = (id) => {
  scoreDetailRef.value?.init(id)
}
const balanceDetailRef = ref(null)
// 余额明细
const initBalanceDetail = (id) => {
  balanceDetailRef.value?.init(id)
}

const couponDetailRef = ref(null)
// 优惠券明细
const initCouponDetail = (id) => {
  couponDetailRef.value?.init(id)
}

const growthDetailRef = ref(null)
// 调用成长值记录组件方法
const initGrowthDetail = (id) => {
  growthDetailRef.value?.init(id)
}
// 修改名称或者状态完成后刷新详情
const onRefreshInfo = () => {
  init(dataForm.value.userId)
  emit('refreshDataList', page)
}
/**
 * 关闭回调
 */
const onHandleDialogClose = () => {
  Object.assign(distributionUser, {
    parentName: null,
    bindTime: null,
    state: null
  })
}

</script>

<style lang="scss" scoped>
.component-user-add-or-update {
  :deep(.user-update-dialog) {
    .el-tabs__content {
      overflow: auto;
    }
    .user-edit-table {
      margin-bottom: 20px;
    }
  }
  :deep(.el-tag) {
    margin-right: 10px;
  }
}

</style>
